package com.itheima.reggie.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.SecureUtil;
import com.alibaba.druid.util.StringUtils;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Employee;
import com.itheima.reggie.mapper.EmployeeMapper;
import com.itheima.reggie.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;


@Service
@Transactional
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    public EmployeeMapper employeeMapper;
    @Override
    public ResultInfo login(String username, String password) {
        //1.根据username查询，如果不存在返回用户名不存在
        Employee employee = employeeMapper.findByUsername(username);
        if(employee == null){
            return ResultInfo.error("用户名不存在");
        }
        //2.前端密码加密之后 VS 数据库查询到的密码  如果失败,返回密码错误
        String passwordWithMd5 = SecureUtil.md5(password);
        if (!StringUtils.equals(passwordWithMd5,employee.getPassword())){
            return ResultInfo.error("密码错误");
        }
        //3. 校验用户状态,如果是禁用,返回禁用状态
        if (employee.getStatus() == Employee.STATUS_DISABLE){
            return ResultInfo.error("当前用户位于禁用状态,不允许登录");
        }
        //4. 如果上面条件都通过,返回登录成功
        return ResultInfo.success(employee);
    }

    @Override
    public List<Employee> findByName(String name) {
        return employeeMapper.findByName(name);
    }
   //新增员工
    @Override
    public void save(Employee employee) {
        //补全前端未传的数据
        employee.setId(IdUtil.getSnowflake(1,1).nextId());//雪花算法
        employee.setPassword(SecureUtil.md5("123456"));//密码默认123，并且加密
        employee.setStatus(employee.STATUS_ENABLE);
       // employee.setCreateTime(new Date());
        //employee.setUpdateTime(new Date());
       // employee.setCreateUser(1L);
       // employee.setUpdateUser(1L);
        //调用mapper层的保存方法
        employeeMapper.save(employee);
    }
   //查询通过id
    @Override
    public Employee findById(long id) {

        return employeeMapper.findById(id);
    }
     //保存
    @Override
    public void update(Employee employee) {
        //重新修改update
        //employee.setUpdateTime(new Date());
        //employee.setUpdateUser(1L);
        //调用mapper的update方法
        employeeMapper.update(employee);

    }
}
